package textTranslateModel

import (
	"encoding/base64"
	"encoding/json"
	"fmt"
	"log"
	"myproject/ttsModel"
	"net/http"
)

type TranslateRequest struct {
	Text             string `json:"text"`
	From             string `json:"from"`
	To               string `json:"to"`
	IsPlayAudioIndex int    `json:"isPlayAudio"`
	AudioVoiceIndex  int    `json:"audioVoice"`
}

type TranslateResponse struct {
	TranslatedText string `json:"translatedText"`
	AudioData      string `json:"audioData"` // 改为 Base64 字符串
	Error          string `json:"error,omitempty"`
}

func TextTranslateHandler(w http.ResponseWriter, r *http.Request) {
	log.Println("收到文本翻译请求")
	w.Header().Set("Access-Control-Allow-Origin", "*")
	w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
	w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
	if r.Method == "OPTIONS" {
		w.WriteHeader(http.StatusOK)
		return
	}

	// fmt.Println(r.Header["Content-Type"])
	// fmt.Println(r.Body)

	var req TranslateRequest
	err := json.NewDecoder(r.Body).Decode(&req)
	if err != nil {
		http.Error(w, "解析请求体失败: "+err.Error(), http.StatusBadRequest)
		return
	}

	languageSource := req.From
	languageTarget := req.To
	selectVoiceIndex := req.AudioVoiceIndex
	IsPlayAudioIndex := req.IsPlayAudioIndex
	fmt.Println(selectVoiceIndex)
	var res TranslateResponse
	w.Header().Set("Content-Type", "application/json")
	res.TranslatedText = Qwen_mt_plus(req.Text, languageSource, languageTarget)

	res.AudioData = ""
	if IsPlayAudioIndex == 0 {
		audioData := ttsModel.SpeechSynthesis(res.TranslatedText, languageTarget, selectVoiceIndex)
		res.AudioData = base64.StdEncoding.EncodeToString(audioData)
	}

	w.Header().Set("Content-Type", "application/json")
	err = json.NewEncoder(w).Encode(res)
	if err != nil {
		return
	}
	log.Println("返回翻译结果")
}
